package com.uikoo9.z;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.uikoo9.manage.y.model.YIsaydetailModel;
import com.uikoo9.manage.y.model.YSettingModel;
import com.uikoo9.manage.y.util.StringUtil;
import com.uikoo9.util.core.data.QStringUtil;
import com.uikoo9.util.function.QCacheUtil;
import com.uikoo9.util.jfinal.QJfinalUtil;
import com.uikoo9.util.jfinal.ucenter.model.UcenterUserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义拦截器，区别于jar中的QInterceptor
 *
 * @author qiaowenbin
 */
public class MyInterceptor implements Interceptor {
    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    @Override
    public void intercept(ActionInvocation ai) {
        String res = checkAuth(ai);
        if (res == null) {
            ai.invoke();
        }

        if ("reload".equals(ai.getController().getPara())) {
            QCacheUtil.removeEHCache("menus-a");
            QCacheUtil.removeEHCache("menus");
            QCacheUtil.removeEHCache("blogTypes");
            QCacheUtil.removeEHCache("base");
            ai.getController().redirect("/");
        }

        HttpServletRequest request = ai.getController().getRequest();
        request.setAttribute("menus", YSettingModel.dao.findAllByCache(checkMenu(ai.getActionKey())));
        Map _color = new HashMap();
        String _icons = "ok";//,th-list,heart,info-sign,eye-open,remove
        for (String _icon : _icons.split(",")) {
            _color.put(_icon + "0", "white");
            _color.put(_icon + "1", "white");
            _color.put(_icon + "5", "white");
            if ("ok".equals(_icon)) {
                _color.put(_icon + "10", "red");
            } else {
                _color.put(_icon + "10", "white");
            }
        }
        request.setAttribute("stausColorMap", _color);
        request.setAttribute("StringUtil", new StringUtil());

        //处理权限 isay
        if (ai.getActionKey().contains("isaydetail")) {
            boolean manage = false;
            if (isAdmin(ai)) {
                manage = true;
            } else {
                UcenterUserModel user = ai.getController().getAttr("user");
                if (user != null) {
                    Integer id = user.getInt("id");
                    Integer isayid = ai.getController().getParaToInt(1);
                    Map param = new HashMap();
                    param.put("cuser_id", id);
                    param.put("id", isayid);
                    List<YIsaydetailModel> list = YIsaydetailModel.dao.find(null, param);
                    if (list.size() > 0) {
                        manage = true;
                    }
                }
            }
            request.setAttribute("manage", manage);
        }
    }

    /**
     * 检测前
     *
     * @return
     */
    private Map<String, String> checkMenu(String actionkey) {
        Map _check = new HashMap();
        _check.put("manage", StringUtil.valueOf(actionkey).contains("manage"));
        return _check;
    }

    public boolean isAdmin(ActionInvocation ai) {
        UcenterUserModel user = ai.getController().getAttr("user");
        if (user != null) {
            String userName = user.getStr("ucenter_user_name");
            if ("uikoo9".equals(userName)) return true;
            String type = user.getStr("ucenter_user_type");
            if ("010101".equals(type)) return true;
        }
        return false;
    }

    /**
     * 是否有权限访问  todo 改成黑名单
     *
     * @param ai
     * @return
     */
    public String authVisit(ActionInvocation ai) {
        try {
            UcenterUserModel user = ai.getController().getAttr("user");
            if (user != null) {
                String userName = user.getStr("ucenter_user_name");
                if ("uikoo9".equals(userName)) return null;
                String type = user.getStr("ucenter_user_type");
                if ("010101".equals(type)) return null;
                /*String urls = getAuths().get("user-" + userName);
                String actionKey = ai.getActionKey();
                for(String url : urls.split(",")){
                    if(actionKey.equals(url)){
                        return null;
                    }
                }*/

                return user.role().getStr("ucenter_role_login_url");
            }
        } catch (Exception e) {
            logger.error(QStringUtil.fromException(e));
        }

        return "/error/auth";
    }

    @SuppressWarnings("unchecked")
    private Map<String, String> getAuths() {
        Map<String, String> urls = null;
        Object urlsObject = QCacheUtil.getFromEHCache("auths");
        if (urlsObject == null) {
            urls = QJfinalUtil.initAuths();
        } else {
            urls = (Map<String, String>) urlsObject;
        }

        return urls;
    }

    /**
     * 屏蔽掉演示系统的一些权限，自己使用的时候可以修改或去掉
     *
     * @param ai
     * @return
     */
    private String checkAuth(ActionInvocation ai) {
        String url = ai.getActionKey();
        Controller cl = ai.getController();

        System.out.println(url + "---------------------------" + cl);
//        return authVisit(ai);
        return null;

        /*
        // 禁止修改密码
		if("/login/modifyPwd".equals(url)){
			return "禁止修改密码";
		}
		
		// 禁止修改默认博客
		if("/blog/edit".equals(url) && "32".equals(cl.getPara())){
			return "禁止修改默认博客";
		}
		
		// 禁止修改，删除默认博客分类
		if("/blog/type/save".equals(url) && "10".equals(cl.getPara("row.id"))){
			return "禁止修改默认博客分类";
		}
		if("/blog/type/del".equals(url)){
			String ids = cl.getPara("ids");
			if(QStringUtil.notEmpty(ids)){
				for(String id : ids.split(",")){
					if("10".equals(id)){
						return "禁止删除默认博客分类";
					}
				}
			}
		}
		
		// 禁止修改，删除默认博客
		if("/blog/article/save".equals(url) && "32".equals(cl.getPara("row.id"))){
			return "禁止修改默认博客";
		}
		if("/blog/article/del".equals(url)){
			String ids = cl.getPara("ids");
			if(QStringUtil.notEmpty(ids)){
				for(String id : ids.split(",")){
					if("32".equals(id)){
						return "禁止删除默认博客";
					}
				}
			}
		}
		
		// 禁止修改，删除默认评论
		if("/blog/comment/save".equals(url) && ("17".equals(cl.getPara("row.id")) || "18".equals(cl.getPara("row.id")))){
			return "禁止修改默认博客评论";
		}
		if("/blog/comment/del".equals(url)){
			String ids = cl.getPara("ids");
			if(QStringUtil.notEmpty(ids)){
				for(String id : ids.split(",")){
					if("17".equals(id) || "18".equals(id)){
						return "禁止删除默认博客评论";
					}
				}
			}
		}
		
		// 禁止修改，删除默认用户
		if("/ucenter/user/save".equals(url) && ("2".equals(cl.getPara("row.id")) || "4".equals(cl.getPara("row.id")))){
			return "禁止修改默认用户";
		}
		if("/ucenter/user/del".equals(url)){
			String ids = cl.getPara("ids");
			if(QStringUtil.notEmpty(ids)){
				for(String id : ids.split(",")){
					if("2".equals(id) || "4".equals(id)){
						return "禁止删除默认用户";
					}
				}
			}
		}
		
		// 禁止修改，删除默认角色
		if("/ucenter/role/save".equals(url) && ("4".equals(cl.getPara("row.id")))){
			return "禁止修改默认角色";
		}
		if("/ucenter/role/del".equals(url)){
			String ids = cl.getPara("ids");
			if(QStringUtil.notEmpty(ids)){
				for(String id : ids.split(",")){
					if("4".equals(id)){
						return "禁止删除默认角色";
					}
				}
			}
		}
		
		// 默认角色禁止分配用户
		if("/ucenter/role/addUser".equals(url) && ("4".equals(cl.getPara("roleid")))){
			return "禁止为默认角色分配用户";
		}
		if("/ucenter/role/removeUser".equals(url) && ("4".equals(cl.getPara("roleid")))){
			return "禁止为默认角色移除用户";
		}
		if("/ucenter/role/saveUrl".equals(url) && ("4".equals(cl.getPara("roleid")))){
			return "禁止为默认角色分配权限";
		}
		
		// 禁止删除，修改和添加菜单
		if("/ucenter/menu/del".equals(url)){
			return "禁止删除菜单";
		}
		if("/ucenter/menu/save".equals(url)){
			return "禁止修改和添加菜单";
		}*/

    }

}
